//遍历时需要两个指针：k指向不被大于right元素阻隔的最左边的元素，p指向上个在[left,right]区间内的元素
//计数时根据当前nums[i]的大小分成两类计数
public class Solution795 {
    public int numSubarrayBoundedMax(int[] nums, int left, int right) {
        int k=-1,ans=0,p=-1;
        for (int i=0;i<nums.length;i++){
            if (nums[i]>right){
                k=p=-1;
                continue;
            }
            if (k==-1 && nums[i]<=right){
                k=i;
            }
            if (nums[i]<=right && nums[i]>=left){
                p=i;
            }
            if (nums[i]<left){
                ans+=p==-1?0:p-k+1;
            }else{
                ans+=k==-1?0:i-k+1;
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(new Solution795().numSubarrayBoundedMax(new int[]{2,5,3,0,1},4,6));
    }
}
